package cn.livingCloud.controller.user.validator;

import cn.livingCloud.dto.AccountChangePasswordDto;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

/**
 * Created by DingJie  on 2016/1/13.
 */
@Component
public class AccountChangePasswordDtoValidator implements Validator {
    @Override
    public boolean supports(Class<?> aClass) {
        return AccountChangePasswordDto.class.equals(aClass);
    }

    public void validate(Object target, Errors errors) {
        AccountChangePasswordDto userAccountDto = (AccountChangePasswordDto) target;
        validatePassword(userAccountDto, errors);
    }

    private void validatePassword(AccountChangePasswordDto userAccountDto, Errors errors) {
        if (StringUtils.isEmpty(userAccountDto.getNewPassword())) {
            errors.rejectValue("newPassword", null, "新密码不能为空");
            return;
        }
        if (StringUtils.isEmpty(userAccountDto.getConfirmPassword())) {
            errors.rejectValue("confirmPassword", null, "确认密码不能为空");
            return;
        }
        if (!userAccountDto.getNewPassword().equals(userAccountDto.getConfirmPassword())) {
            errors.rejectValue("confirmPassword", null, "密码和确认密码不同");
        }
    }
}
